package 网络编程项目.login;

import 网络编程项目.login.entity.User;
import 网络编程项目.login.utiles.ClientUtil;
import 网络编程项目.login.utiles.ImageUtil;
import 网络编程项目.login.utiles.JsonUtil;
import 网络编程项目.pojo.Message;
import 网络编程项目.pojo.MessageType;
import 网络编程项目.pojo.Response;
import 网络编程项目.util.PathUtils;

import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;


public class Login {
  private JPanel login;
  private JTextField useridField;
  private JPasswordField passwordField;
  private JButton loginButton;
  private JButton registerButton;
  private JLabel image;
  public static JFrame frame = new JFrame("Login");
  private static ClientUtil clientUtil = new ClientUtil();
  public static SocketChannel socketChannel = null;
  private static Response response = null;
  public static String username;


  public Login() {
    ImageIcon icon = ImageUtil.change(new ImageIcon(PathUtils.imgDir+"/QQLogol.jpg"), 100);
    image.setIcon(icon);
    loginButton.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        User user = new User();
        user.setUserid(useridField.getText());
        String password = new String(passwordField.getPassword());
        user.setPassword(password);
        String userString = JsonUtil.UserToString(user);
        username = useridField.getText();
        if ("".equals(useridField.getText()) || "".equals(new String(passwordField.getPassword()))) {
          UserNameOrPasswordIsNull.main();
          return;
        }

        Message msg = new Message();
        msg.setMsg(userString);
        msg.setType(MessageType.LOGIN);
        clientUtil.sendMessage(socketChannel, msg);

      }
    });

    registerButton.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        frame.setVisible(false);
        Register.main(socketChannel);
      }
    });
  }

  public static void main(SocketChannel channel) {
    socketChannel = channel;
    frame.setContentPane(new Login().login);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    frame.setLocation(600, 350);
  }
}
